package com.example.java.escape.thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author : weicai
 * @date : 15:23 2020/11/28
 *
 * 简单线程池实现
 */
public class UserThreadPool {
    public static void main(String[] args) {

        // 缓存队列设置固定长度为2，为了快速触发 rejectHandler
        BlockingQueue queue = new LinkedBlockingQueue(2);

        // 设置外部任务线程的来源由1号房和2号房混合调用
        UserThreadFactory f1 = new UserThreadFactory("第 1 机房");
        UserThreadFactory f2 = new UserThreadFactory("第 2 机房");

        UserRejectHandler handler = new UserRejectHandler();

        // 核心线程数：1，容纳同时执行线程数：2，空闲时间：60，时间单位：秒，缓存队列：queue，线程工厂：f1，拒绝策略：handler
        ThreadPoolExecutor threadPoolFirst = new ThreadPoolExecutor(1, 2,60 , TimeUnit.SECONDS, queue, f1, handler);
        ThreadPoolExecutor threadPoolSecond = new ThreadPoolExecutor(1, 2,60 , TimeUnit.SECONDS, queue, f2, handler);

        Runnable task = new UserThreadFactory.Task();
        // 创建10个任务线程
        for (int i=0; i <= 10; i++) {
            threadPoolFirst.execute(task);
            threadPoolSecond.execute(task);
        }
        threadPoolFirst.shutdown();
        threadPoolSecond.shutdown();
    }
}
